package com.spring.handler;

import java.io.*;

/**
 * @author Spring King
 * @date 2021/7/11
 */
public class WebClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String moduleName, String name) {
        byte[] classBytes = getClassBytes(moduleName, name);
        return defineClass(name, classBytes, 0, classBytes.length);
    }

    private byte[] getClassBytes(String moduleName, String name) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        String path = moduleName + File.separator + name.replace(".", File.separator) + ".class";
        try {
            inputStream = new FileInputStream(path);
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }
}
